package com.atguigu.gmall.order.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
@Slf4j
public class RabbitmqConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack){
                // 记录日志 或者 记录到数据库，将来可以通过定时任务重新发送
                log.error("消息么有到达交换机。原因：{}, 元信息：{}", cause, correlationData.toString());
            }
        });
        this.rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.error("消息没有到达队列。状态码：{}，状态文本：{}，交换机：{}，路由键：{}，消息内容：{}", replyCode, replyText, exchange, routingKey, new String(message.getBody()));
        });
    }

    /**
     * 延时队列 order_ttl_queue
     */
    @Bean
    public Queue queue(){
        return QueueBuilder.durable("order_ttl_queue")
                .ttl(90000).deadLetterExchange("ORDER_CREATE_EXCHANGE")
                .deadLetterRoutingKey("death.order").build();
    }

    /**
     * 延时交换机 ORDER_CREATE_EXCHANGE
     */



    /**
     * 延时队列绑定到延时交换机 ttl.order
     */
        @Bean
    public Binding binding(){
           return new Binding("order_ttl_queue", Binding.DestinationType.QUEUE
           ,"ORDER_CREATE_EXCHANGE","ttl.order",null);
        }

    /**
     * 死信队列 order_death_queue
     */
    @Bean
    public Queue deadQueue(){

        return QueueBuilder.durable("order_death_queue").build();
    }

    /**
     * 延时队列绑定到延时交换机 death.order
     */
    @Bean
    public Binding deadBinding(){
        return new Binding("order_death_queue", Binding.DestinationType.QUEUE
        ,"ORDER_CREATE_EXCHANGE","death.order",null);
    }

}
